<template>
    <view class="content">
        <view class="bg"></view>
        
        <view v-for="(item, index) in list" :key="index">
            <view class="box">
                <view class="work-title" v-if="index == 0">发货明细</view>
                <view class="item">
                    <view class="grey">货物类型</view>
                    <view class="item-right" @click="openGoodsType(item)">
                        <input type="text" v-model="item.type" placeholder="请选择货物类型" class="inp" disabled>
                        <u-icon name="arrow-right" color="#979797" size="28" class="u-m-l-5"></u-icon>
                    </view>
                </view>
                <view class="item">
                    <view class="grey">产品名称</view>
                    <view class="item-right" @click="openGoodsName(item)">
                        <input type="text" v-model="item.goods" placeholder="请选择产品名称" class="inp" disabled>
                        <u-icon name="arrow-right" color="#979797" size="28" class="u-m-l-5"></u-icon>
                    </view>
                </view>
                <view class="item">
                    <view class="grey">件数</view>
                    <view class="item-right">
                        <input type="number" v-model="item.num" placeholder="请输入件数" class="inp" @blur="blur(item)">
                        <text class="u-p-l-10 text-bold">件</text>
                    </view>
                </view>
            </view>
            <view class="btns">
                <image src="../../static/icon/add_02.png" class="add-02" @click="addShipping"></image>
                <image src="../../static/icon/del.png" class="del-02" v-if="list.length > 1" @click="delShipping(index)"></image>
            </view>
        </view>
        
        <view class="box">
            <view class="item">
                <view class="grey">总件数</view>
                <view class="item-right">
                    <input type="number" v-model="totalNum" placeholder="自动计算" class="inp" disabled>
                    <text class="u-p-l-10 text-bold">件</text>
                </view>
            </view>
            <view class="item">
                <view class="grey">预估总重量</view>
                <view class="item-right">
                    <input type="text" v-model="weight" placeholder="请输入预估总重量" class="inp">
                    <text class="u-p-l-10 text-bold">斤(500g/斤)</text>
                </view>
            </view>
            <view class="item u-p-b-10">
                <view class="grey">预计装货时间</view>
                <view class="item-right">
                    <input type="text" v-model="time" placeholder="开始" class="inp-zh" disabled @click="show_3 = true">
					<text class="u-p-l-15 u-p-r-15">-</text>
					<input type="text" v-model="time2" placeholder="结束" class="inp-zh" disabled @click="show_4 = true">
                    <!-- <u-icon name="arrow-right" color="#979797" size="28" class="u-m-l-5"></u-icon> -->
                </view>
            </view>
            <view class="item-col">
                <view class="grey">货物备注</view>
                <textarea v-model="goods_remark" maxlength="200" :auto-height="true" placeholder="请输入货物备注信息" class="t-inp"></textarea>
            </view>
        </view>
        
        <view class="btn" @click="$noMultipleClicks(next)">下一步</view>
		
		<!-- 货物类型 -->
		<template v-if="show_1">
			<u-select v-model="show_1" mode="single-column" :list="goodsTypeList" label-name="name" value-name="id" @confirm="confirm($event, 1)"></u-select>
		</template>
		
		<!-- 产品名称 -->
		<u-popup mode="bottom" v-model="show_2">
		    <view class="popup">
		        <u-search placeholder="请输入产品名称" v-model="keyword" :show-action="false" @search="doSearch"></u-search>
		        <scroll-view scroll-y="true" style="height: 500rpx;">
		            <view>
		                <view class="popup-item" v-for="(item, index) in goodsNameList" :key="index"
		                    :class="{active : item.isSelect}" @click="choose(item)">
		                    {{item.name}}
		                </view>
		            </view>
					<view style="text-align: center;padding: 50upx 0;color: #999;font-size: 24rpx;" v-if="goodsNameList.length == 0">暂无相关信息</view>
		        </scroll-view>
		        <view class="pop-btn" @click="confirmGood">确定</view>
		    </view>
		</u-popup>
		
		<!-- 装车时间 -->
		<template v-if="show_3">
			<u-select v-model="show_3" mode="single-column" :list="timeList" @confirm="confirm($event, 3)"></u-select>
		</template>
		<template v-if="show_4">
			<u-select v-model="show_4" mode="single-column" :list="timeList" @confirm="confirm($event, 4)"></u-select>
		</template>
    </view>
</template>

<script>
    export default {
        data() {
            return {
				noClick: true,//连点
				line_id: '',//线路id
				show_1: false,//货物类型
				show_2: false,//产品名称
				show_3: false,//预计装货时间-开始
				show_4: false,//预计装货时间-结束
				goodsTypeList: [],//货物类型
				goodsNameList: [],//产品名称
				timeList: [],
				time: '',//预计装货时间-开始
				time2: '',//预计装货时间-结束
                list: [{type: '',type_id:'',goods:'',goods_id:'',num:''}],
				item: {},
				totalNum: '',//总件数
				weight: '',//预估总重量
				goods_remark: '',//货物备注
				keyword: '',
				order_id: '',
				isAgain: '',//1是再来一单
				order_id_again: '',//再来一单的id
            };
        },
        onLoad(option) {
			if (option.isAgain) {
				this.isAgain = option.isAgain
				this.order_id_again = option.order_id_again
			}
			if (option.order_id) {
				this.order_id = option.order_id
				this.getData()
			}
        },
		onShow() {
			
		},
        methods: {
			// 再来一单时，获取重新选择的发货日期和时间
			getData2() {
				this.$ajax('orders_detail', {
						user_token: this.$getSync('userToken'),
						order_id: this.order_id,//订单id
					}).then(ret => {
				    if (ret.success == 1000) {
						let data = ret.detail
						
						// 第二步的数据
						if (data.goods && data.goods.length > 0) {
							this.list = data.goods
							this.totalNum = data.num//总件数
							this.weight = data.weight //预估总重量
							
							if (!this.isAgain) {
								let t = data.loading_time.split("-")
								this.time = t[0]
								this.time2 = t[1]
							}
							
							this.goods_remark = data.goods_remark
						}
						
						this.date = data.start_date
						// 生成可选的装车时间列表
						let b = data.start_time.split(":")[0] //发车时间，装车时间要在发车时间前
						let c = Number(b)
						for (let i = 0; i <= c; i++) {
							let lab = i < 10 ? '0' + i : i
							this.timeList.push({
								value: i,
								label: lab + ':00'
							})
						}
						
						this.line_id = data.line_id
						this.getGoodsType()
						
				    } else {
				        this.$toast(ret.msg);
				    }
				});
			},
			
			// 获取订单详情
			getData() {
				let url = '', param = {}
				if (this.isAgain) {
					// 再来一单
					url = 'another_order'
					param = {
						user_token: this.$getSync('userToken'),
						order_id: this.order_id_again,//订单id
					}
				} else {
					// 订单详情
					url = 'orders_detail'
					param = {
						user_token: this.$getSync('userToken'),
						order_id: this.order_id,//订单id
					}
				}
			    this.$ajax(url, param).then(ret => {
			        if (ret.success == 1000) {
						let data = ret.detail
						
						// 第二步的数据
						if (data.goods && data.goods.length > 0) {
							this.list = data.goods
							this.totalNum = data.num//总件数
							this.weight = data.weight //预估总重量
							if (!this.isAgain) {
								let t = data.loading_time.split("-")
								this.time = t[0]
								this.time2 = t[1]
							}
							this.goods_remark = data.goods_remark
						}
						
						if (!this.isAgain)  {
							this.date = data.start_date
							// 生成可选的装车时间列表
							let b = data.start_time.split(":")[0] //发车时间，装车时间要在发车时间前
							let c = Number(b)
							for (let i = 0; i <= c; i++) {
								let lab = i < 10 ? '0' + i : i
								this.timeList.push({
									value: i,
									label: lab + ':00'
								})
							}
							
							this.line_id = data.line_id
							this.getGoodsType()
						} else {
							this.getData2()
						}
						
			        } else {
			            this.$toast(ret.msg);
			        }
			    });
			},
			
            // 下一步
            next() {
				let data = [], isNull = false
				this.list.forEach(cur => {
					if (!cur.type_id || !cur.goods_id || !cur.num) {
						isNull = true
					}
				})
				if (isNull) {
					this.$toast('请将发货明细填写完整')
					return
				}
				this.list.forEach(cur => {
					data.push({
						type_id: cur.type_id,
						goods_id: cur.goods_id,
						num: cur.num
					})
				})
				if (!this.weight) {
					this.$toast('请输入预估总重量')
					return
				}
				if (!this.time) {
					this.$toast('请选择预估装车开始时间')
					return
				}
				if (!this.time2) {
					this.$toast('请选择预估装车结束时间')
					return
				}
				
				this.$ajax('insert_order_second', {
				    user_token: this.$getSync('userToken'),
					order_id: this.order_id,//订单id
					loading_time: this.time + '-' + this.time2,//预估装车时间
					carriage_id: '',//车厢id 零担
					weight: this.weight,//预估重量 包车
					goods_remark: this.goods_remark,//货物备注
					data: data,//[{"type_id":3,"goods_id":4,"brand_id":"13","model_id":"36","package_id":"37","num":20}]
					//type_id货物类型id，goods_id产品id，brand_id品牌id，model_id型号id，package_id包装id 零担重量模板必填，num件数
				}).then(ret => {
				    if (ret.success == 1000) {
				        this.$gTo(`/pages/bus/bus-confirm?order_id=${ret.detail.order_id}`)
				    } else {
				        this.$toast(ret.msg);
				    }
				});
            },
			
			// 计算总件数
			blur() {
				this.totalNum = 0
				this.list.forEach(cur => {
					this.totalNum = Number(this.totalNum) + Number(cur.num)
				})
			},
			
			// 添加发货明细
			addShipping() {
			    this.list.push({type: '',type_id:'',goods:'',goods_id:'',num:''})
			},
			
			// 删除发货明细
			delShipping(index) {
			    this.list.splice(index, 1)
				this.blur()
			},
            
			openGoodsType(item) {
				this.item = item
				this.show_1 = true
			},
			
			openGoodsName(item) {
				if (!item.type_id) {
					this.$toast('请先选择货物类型')
					return
				} else {
					this.getGoodsName(item.type_id)
					this.item = item
					setTimeout(() => {
						this.show_2 = true
					},100)
				}
			},
			
			// 选择产品名称
			choose(item) {
				const nowStatu = item.isSelect
				this.goodsNameList.forEach(ii => {
				    ii.isSelect = false
				})
				item.isSelect =! nowStatu
			},
			confirmGood() {
			    if (this.goodsNameList && this.goodsNameList.length > 0) {
			        this.goodsNameList.forEach(cur => {
			            if (cur.isSelect) {
							this.item.goods = cur.name
							this.item.goods_id = cur.id
			            }
			        })
			    }
			    this.show_2 = false
			},
			// 搜索产品名称
			doSearch() {
			    this.getGoodsName(this.item.type_id)
			},
			
			confirm(e, num) {
				console.log(e);
				const currentDate = new Date();
				const year = currentDate.getFullYear();
				const month = currentDate.getMonth() + 1; // 月份从0开始，需要加1
				const day = currentDate.getDate();
				const now = new Date(year + '-' + (month > 10 ? month : '0' + month) + '-' + (day > 10 ? day : '0' + day))//当前日期
				
				if(num == 1) {
					// 货物类型
					this.item.type = e[0].label
					this.item.type_id = e[0].value
					this.item.goods = ''
					this.item.goods_id = ''
					
				} else if(num == 3) {
					// 预计装货时间--开始
					let date = new Date(this.date).getTime()//选择的发车日期
					let nowstamp = now.getTime()
					
					let end_time_s
					if (this.time2) { end_time_s = this.time2.split(":"); }
					let now_time_s = e[0].label.split(":");
					if (this.time2 && currentDate.setHours(now_time_s [0],now_time_s [1]) >= currentDate.setHours(end_time_s [0],end_time_s [1])) {
						this.$toast('结束时间不能小于等于开始时间')
						this.time = ''
						return
					} else {
						this.time = e[0].label
						
						// if (date == nowstamp) {
						// 	// 如果是当天，判断预计装货时间 不能 小于当前时间
						// 	let currentTime = new Date();
						// 	let nowh = currentTime.getHours();//当前 小时
						// 	let hours = Number(e[0].value)//选择的小时
						// 	console.log(hours,nowh)
						// 	if (nowh >= hours) {
						// 		this.$toast('不能选择过去的时间')
						// 		return
						// 	} else {
						// 		this.time = e[0].label
						// 	}
						// } else {
						// 	this.time = e[0].label
						// }
					}
				} else if(num == 4) {
					// 预计装货时间--结束
					let date = new Date(this.date).getTime()//选择的发车日期
					let nowstamp = now.getTime()
					
					let now_time_s
					if (this.time) { now_time_s = this.time.split(":"); }
					let end_time_s = e[0].label.split(":");
					
					if (this.time && currentDate.setHours(now_time_s [0],now_time_s [1]) >= currentDate.setHours(end_time_s [0],end_time_s [1])) {
						this.$toast('结束时间不能小于等于开始时间')
						this.time2 = ''
						return
					} else {
						if (date == nowstamp) {
							// 如果是当天，判断预计装货时间 不能 小于当前时间
							let currentTime = new Date();
							let nowh = currentTime.getHours();//当前 小时
							let hours = Number(e[0].value)//选择的小时
							// console.log(hours,nowh)
							if (nowh >= hours) {
								this.$toast('不能选择过去的时间')
								return
							} else {
								this.time2 = e[0].label
							}
						} else {
							this.time2 = e[0].label
						}
					}
				}
				// console.log(this.time2 <= this.time,this.time2 , this.time)
			},
			
			// 获取产品名称
			getGoodsName(type_id) {
			    this.$ajax('select_goods', {
			        user_token: this.$getSync('userToken'),
					line_id: this.line_id,//线路id
					type_id: type_id,//类型id
					name: this.keyword,//搜索
			    }).then(ret => {
			        if (ret.success == 1000) {
			            this.goodsNameList = ret.detail
						if (this.goodsNameList && this.goodsNameList.length > 0) {
						    this.goodsNameList.forEach(cur => {
								this.$set(cur, 'isSelect', false)
						    })
						}
			        } else {
			            this.$toast(ret.msg);
			        }
			    });
			},
			
			// 获取货物类型
			getGoodsType() {
			    this.$ajax('goods_type', {
			        user_token: this.$getSync('userToken'),
					line_id: this.line_id,//线路id
			    }).then(ret => {
			        if (ret.success == 1000) {
			            this.goodsTypeList = ret.detail
			        } else {
			            this.$toast(ret.msg);
			        }
			    });
			},
        }
    };
</script>

<style lang="scss">
	.inp-zh{
		background-color: #f5f5f5;
		text-align: center;
		height: 60rpx;
	}
	.popup{
	    padding: 24rpx;
	}
	.popup-item{
	    padding: 20rpx 0;
	    text-align: center;
	}
	.active{
	    font-weight: bold;
	    color: #00a1e9;
	}
	.pop-btn{
	    color: #fff;
	    background-color: #00a1e9;
	    padding: 20rpx;
	    text-align: center;
	    margin: 20rpx;
	    border-radius: 50rpx;
	}
    
    page{
        background-color: #f2f4fa;
    }
    .content {
    	padding: 30rpx 20rpx;
    }
    .bg {
    	width: 100%;
    	height: 500rpx;
    	position: absolute;
    	top: 0;
    	left: 0;
    	z-index: -1;
    	background: linear-gradient(to bottom, #cfe4fc, #e5eefb,#f2f4fa);
    }
    
    .box{
        padding: 0 30rpx;
        background-color: #fff;
        border-radius: 20rpx;
        margin-bottom: 30rpx;
    }
    
    .item{
        padding: 30rpx 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .work-title{
        font-size: 32rpx;
        font-weight: bold;
        padding-top: 30rpx;
    }
    .item-right{
        flex: 1;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding-left: 15rpx;
    }
    .inp{
        flex: 1;
        text-align: right;
    }
    .grey{
        color: #656565;
    }
    .price{
        padding: 30rpx 0 20rpx;
        border-top: 2rpx solid #f4f4f4;
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        font-size: 28rpx;
    }
    .price-num{
        font-size: 40rpx;
        font-weight: bold;
        padding-left: 10rpx;
        padding-right: 5rpx;
    }
    .tip{
        font-size: 22rpx;
        color: #fe6a00;
        line-height: 1;
        padding: 5rpx 13rpx;
        background-color: #fdf6f0;
        border: 2rpx solid #fe6a00;
        margin-top: 8rpx;
    }
    
    .btns{
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding-bottom: 40rpx;
    }
    .add-02{
        width: 152rpx;
        height: 56rpx;
    }
    .del-02{
        width: 57rpx;
        height: 57rpx;
        margin-left: 25rpx;
    }
    
    .pt-box{
        padding: 35rpx 30rpx;
        background-color: #fff;
        border-radius: 20rpx;
        margin-bottom: 16rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .icon-02{
        width: 55rpx;
        height: 55rpx;
        margin-right: 15rpx;
    }
    .pt-t1{
        font-size: 32rpx;
        font-weight: bold;
        padding-right: 20rpx;
    }
    .pt-t2{
        font-size: 22rpx;
        color: #929292;
    }
    .pt-t3{
        font-size: 22rpx;
        color: #ff5f2b;
    }
    
    .price2{
        display: flex;
        flex-direction: column;
        align-items: flex-end;
    }
    .tip2{
        font-size: 22rpx;
        color: #fe6a00;
        line-height: 1;
        padding: 5rpx 13rpx;
        background-color: #fdf6f0;
        border: 2rpx solid #fe6a00;
    }
    
    .item-col{
        padding: 30rpx 0;
    }
    .option{
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        align-items: center;
        padding-top: 10rpx;
    }
    .o-i{
        background-color: #f5f5f5;
        border-radius: 20rpx;
        padding: 20rpx 45rpx;
        margin-top: 13rpx;
        margin-right: 13rpx;
    }
    .active{
        color: #0075cf;
        background-color: #f1f8ff;
        border: 2rpx solid #0075cf;
        box-sizing: border-box;
        position: relative;
    }
    .choose-03{
        width: 33rpx;
        height: 26rpx;
        position: absolute;
        right: 0;
        bottom: 0;
    }
    .t-inp{
        background-color: #f5f6fa;
        width: 100%;
        min-height: 180rpx;
        height: auto;
        padding: 20rpx;
        border-radius: 10rpx;
        margin-top: 20rpx;
    }
    .btn{
        font-size: 34rpx;
        color: #fff;
        text-align: center;
        padding: 25rpx;
        background-color: #00457f;
        border-radius: 50rpx;
        margin-top: 50rpx;
    }
    

</style>
